<template>
	<view class="tui-digital__roller">
		<view class="tui-digital__box" v-for="(item, index) in columns" :key="index" :style="{ width: cellWidth, height: height + 'px' }">
			<view
				class="tui-digital__column"
				:style="{ transform: `translate3d(0, -${keys[index] * height}px, 0)`, transitionDuration: `${duration}s`, transitionTimingFunction: animation }"
			>
				<view
					class="tui-digital__item"
					v-for="(val, idx) in item"
					:key="idx"
					:style="{ color: color, fontSize: size + 'rpx', fontWeight: bold ? 'bold' : 'normal', height: height + 'px', lineHeight: size + 'rpx' }"
				>
					<text>{{ val }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'

// 获取 emit
const emit = defineEmits([])

const props = defineProps({
	value: {
		type: [Number, String],
		default: ''
	},
	color: {
		type: String,
		default: '#f56c6c;'
	},
	//rpx
	size: {
		type: Number,
		default: 32
	},
	bold: {
		type: Boolean,
		default: false
	},
	//滚动行高度 rpx
	cellHeight: {
		type: Number,
		default: 32
	},
	//单个数字宽度
	cellWidth: {
		type: String,
		default: 'auto'
	},
	// 动画过渡效果
	animation: {
		type: String,
		default: 'cubic-bezier(0, 1, 0, 1)'
	},
	//动画时间
	duration: {
		type: Number,
		default: 1.2
	}
})

const state = reactive({
	columns: [],
	keys: [],
	height: 0
})

watch(
	() => props.value,
	nVal => {
		initColumn(nVal)
	}
)

watch(
	() => props.cellHeight,
	nVal => {
		handleHeight(nVal)
	}
)

const handleHeight = h => {
	state.height = uni.upx2px(h || 0)
}

const initColumn = val => {
	val = val + ''
	let digit = val.length,
		arr = [],
		rows = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	for (let i = 0; i < digit; i++) {
		if (val[i] === '.' || val[i] === ',') {
			arr.push(val[i])
		} else {
			arr.push(rows)
		}
	}
	state.columns = arr
	roll(val)
}

const roll = value => {
	let valueArr = value.toString().split(''),
		lengths = state.columns.length,
		indexs = []

	while (valueArr.length) {
		let figure = valueArr.pop()
		if (figure === '.' || figure === ',') {
			indexs.unshift(0)
		} else {
			indexs.unshift(Number(figure))
		}
	}

	while (indexs.length < lengths) {
		indexs.unshift(0)
	}

	state.keys = indexs
	console.log('roll: ', state.keys, state.columns)
}

const { columns, keys, height } = toRefs(state)

handleHeight(props.cellHeight)
initColumn(props.value)
</script>

<style lang="scss" scoped>
.tui-digital__roller {
	display: inline-flex;
	justify-content: space-between;
	align-items: center;
}

.tui-digital__box {
	overflow: hidden;
}

.tui-digital__column {
	transform: translate3d(0, 0, 0);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.tui-digital__item {
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
